package com.aohe.youzi.activity.main;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;

import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.aohe.youzi.Constants;
import com.aohe.youzi.MyApplication;
import com.aohe.youzi.databinding.DialogProgressBinding;
import com.aohe.youzi.http.BaseResponse;
import com.aohe.youzi.http.JsonCallBack;
import com.aohe.youzi.mvp.MvpBasePresenter;
import com.aohe.youzi.utils.MyDialogUtil;
import com.aohe.youzi.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;

import java.io.File;
import java.util.ArrayList;


public class MainPresenter extends MvpBasePresenter<MainContract>  {
    private String TAG = getClass().getSimpleName();

    private String[] permissions = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.BLUETOOTH
    };
    ArrayList<String> per = new ArrayList<>();
    private static final int REQUEST_CODE = 0x004;
    private static int RC_PERMISSION = 3;


    @Override
    public void start() {
        super.start();

        if (!(ActivityCompat.checkSelfPermission(getView().getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
            //没有权限，申请权限
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
            //申请权限，其中RC_PERMISSION是权限申请码，用来标志权限申请的
            ActivityCompat.requestPermissions(getView().getActivity(), permissions, RC_PERMISSION);
        }
        if (!(ActivityCompat.checkSelfPermission(getView().getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
            //没有权限，申请权限
            String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
            //申请权限，其中RC_PERMISSION是权限申请码，用来标志权限申请的
            ActivityCompat.requestPermissions(getView().getActivity(), permissions, RC_PERMISSION);
        }
        checkPermission();
        requestPermission();
    }

    private void checkPermission() {
        for (String permission : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(getView().getActivity(), permission)) {
                per.add(permission);
            }
        }
    }

    private void requestPermission() {
        if (per.size() > 0) {
            String[] p = new String[per.size()];
            ActivityCompat.requestPermissions(getView().getActivity(), per.toArray(p), REQUEST_CODE);
        }
    }



    public void getNewAppInfo() {
        OkGo.<BaseResponse<Version>>get(Constants.getNewAppInfo)
                .tag(this)
                .execute(new JsonCallBack<BaseResponse<Version>>(getView().getActivity(), true, "") {
                    @Override
                    public void onSuccessData(Response<BaseResponse<Version>> response) {
                        try {
                            if (getView() == null) {
                                return;
                            }

                            if (response.body().getStatus() == 200) {
                                Version version = response.body().data;
                                if (version == null) {
                                    return;
                                }
                                getView().showVersionDta(version);
                            } else {
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(String error) {
                        try {
                            if (getView() != null) {
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    public void getApk(String url) {
        showProgressDialog();
        OkGo.<File>get(url)
                .tag(this)
                .execute(new FileCallback(getView().getActivity().getExternalCacheDir().getPath(), "opene.apk") {
                    @Override
                    public void onSuccess(Response<File> response) {
                        if (myDialogProgress != null) {
                            myDialogProgress.dismiss();
                        }
                        File file = response.body();
                        if (file != null) {
                            Log.e(TAG, "file.getPath():" + file.getPath());
                            getView().setApkFile(file);
                        }
                    }

                    @Override
                    public void onError(Response<File> response) {
                        super.onError(response);
                        if (myDialogProgress != null) {
                            myDialogProgress.dismiss();
                        }
                        try {
                            ToastUtil.showToast("Network Error, Please Try Again Later");
                            Log.e(TAG, "请求服务器失败，请稍后再试" + response.message() + "----" + response.getException());
//                            okhttp3.Response rawResponse = response.getRawResponse();
//                            Log.e(TAG, "response.getRawResponse():" + response.getRawResponse());
//                            ResponseBody body = rawResponse.body();
//                            String string = body.string();
//                            if (!string.contains("<head><title>")) {
//                                BaseResponse<Object> baseResponse = FastJsonUtil.getObject(string, BaseResponse.class);
//                                ToastUtil.showToast(baseResponse.getMsg());
//                            } else {
//                                ToastUtil.showToast("Network Error, Please Try Again Later");
//                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            ToastUtil.showToast("Network Error, Please Try Again Later");
                        }
                    }

                    @Override
                    public void downloadProgress(Progress progress) {
                        super.downloadProgress(progress);
                        Log.e(TAG, "downloadProgress():" + progress.fraction);
                        if ((myDialogProgress != null) && (dialogBinding != null) && (dialogBinding.progressbar != null) && (dialogBinding.tvProgress != null)) {
                            dialogBinding.progressbar.setProgress((int) (progress.fraction * 100));
                            dialogBinding.tvProgress.setText((progress.fraction * 100) + "/100");
                        }
                    }
                });
    }


    AlertDialog myDialogProgress;

    private void showProgressDialog() {
        myDialogProgress = MyDialogUtil.getDialog(getView().getActivity(), initProgressDialogView(), Gravity.CENTER);
        myDialogProgress.setCanceledOnTouchOutside(false);
        myDialogProgress.show();
    }

    DialogProgressBinding dialogBinding;

    private View initProgressDialogView() {
        dialogBinding = DialogProgressBinding.inflate(LayoutInflater.from(getView().getActivity()));
        return dialogBinding.getRoot();
    }

    /*
     * 方法名：installingAPK(File file)
     * 功    能：安装apk,适配安卓6.0,7.0,8.0
     * 参    数：File file
     * 返回值：无
     */
    private void installingAPK(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //安卓7.0以上需要在在Manifest.xml里的application里，设置provider路径
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(getView().getActivity(), "com.aohe.youzi.fileprovider", new File(file.getPath()));
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        getView().getActivity().startActivity(intent);
    }


}
